/*
 * TYU计科系 （C）版权所有 2022-3-22
 */
package cn.edu.tyu.finance.thingstype.servlet;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;

import cn.edu.tyu.finance.util.DbUtil;
import cn.edu.tyu.finance.util.StringUtil;

/**
 * 用户登录功能
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
	 * 处理网页发来的get请求
	 * @param request 请求对象 
	 * @param response 响应对象
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.接受用户名和密码
		String uname=request.getParameter("username");
		String upsw=request.getParameter("userpsw");
		String upswMD5=StringUtil.getMD5(upsw);
		//2.连接数据库，查询有无此人
		java.sql.Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		conn=DbUtil.getConnection();
		String sql="SELECT * FROM users WHERE username=? AND userpsw=?";  //带条件的查询，同时两个条件
		try {
			pstmt=conn.prepareStatement(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			pstmt.setString(1, uname);
			pstmt.setString(2, upswMD5);
			rs=pstmt.executeQuery();
			if(rs.next()) { // 有数据返回OK
				response.sendRedirect("ok.jsp");
				
			}else {
				response.sendRedirect("fail.jsp");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			DbUtil.backConn(conn, pstmt, rs);
		}

		}

	 /**
		 * 处理网页发来的post请求
		 * @param request 请求对象 
		 * @param response 响应对象
		 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
